<?php
if (LZ_MODULE != 'phpdisk') die('Access Denied');



$user = $_SESSION['user'];
$root = $user["root"];

$action = $_REQUEST['action'];

$filename = $_GET['filename'];
if (preg_match('/^download\/([a-zA-Z0-9,_=\/]+)\/([^\/]+)$/',$filename,$ms))
{
	$path = '/'.$ms[1];
	$lockfile = false;
}
else if (preg_match('/^lockanddown\/([a-zA-Z0-9,_=\/]+)\/([^\/]+)$/',$filename,$ms))
{
	$path = '/'.$ms[1];
	$lockfile = true;
}
if (substr($path,-1) == '/') $path = substr($path,0,-1);
if (is_dir($path)) $path .= '/';
$path = dealpath($path);

if ($_SESSION['login_user']['status'] == 'admin')
{
	$_path = str_replace($config['document_root'],'',$path);
	if (preg_match('/([a-zA-Z0-9]{32})\/([a-zA-Z0-9]{32})/',$_path,$ms))
	{
		include_once('model/customer.php');
		$customer = new LZ_Customer;
		$arr = $customer->get_one_by_token($ms[2]);
		$customer_id = $arr['company_id'];
	}
	else
	{
		exit("<script>alert('Access Denied');</script>");
	}
}

if (!$path || !$user["downfile"]) exit("<script>alert('$path !Access Denied');</script>");
if (!function_exists('iconv')) exit("<script>alert('no iconv!');</script>");
$path = str_replace("|","",$path);

if ($lockfile)
{
	include_once(LZ_BASEPATH.'model/lock.php');
	$lock = new LZ_Lock;
	if ($l = $lock->exists($path))
	{
		$msg = str_replace(array( '{user}','{time}') , array( $l['user'],format_past_time($l['time'])) ,FILE_LOCKED);
		echo "<script>";
		echo "parent.notice('$msg');";
		echo "</script>";
		die;
	}
	$cid = $_SESSION['login_user']['customer_id'];
	if (!$cid && $customer_id) $cid = $customer_id;
	$lock->add(array(
		'user' => $_SESSION['login_user']['email'],
		'customer_id' => $cid,
		'file' => $path,
		'time' => time()
	));
}

if (!file_exists($path)) exit("<script>alert('".FILE_NOT_FOUND."');</script>");

if (is_file($path))
{
	$filename = name_decode(basename1($path));
//exit("<script>alert(\"" .$filename . "\");</script>");
	if (!preg_match('/Mac/',$_SERVER['HTTP_USER_AGENT']))
	{
//NT 5.0  ---> Windows 2000
//NT 5.1  ---> Windows XP
if (preg_match("/NT 5\.0/",$_SERVER['HTTP_USER_AGENT'])||preg_match("/NT 5\.1/",$_SERVER['HTTP_USER_AGENT'])){
$config['client_charset'] = 'SJIS-WIN';
}
		$filename = iconv("UTF-8",$config['client_charset'],$filename);
		if (!$filename)
		{
			exit("<script>alert('iconv error!');</script>");
		}
	}

	/*
	function html_to_utf8($data) {
    $data= hexdec($data);
    if ($data > 127) {
      $i = 5;
      while (($i--) > 0) {
        if ($data != ($a = $data % ($p = pow(64, $i)))) {
          $ret = chr(base_convert(str_pad(str_repeat(1, $i + 1), 8, "0"), 2, 10) + (($data - $a) / $p));
          for ($i; $i > 0; $i--)
            $ret .= chr(128 + ((($data % pow(64, $i)) - ($data % ($p = pow(64, $i - 1)))) / $p));
            break; }
      }
    } else $ret = "&#$data;";
    return $ret;
  }
  */

	//$filename = preg_replace("/%u([0-9ABCDEFabcdef]{3,5})/e", 'html_to_utf8("\\1")', $filename);
//exit("<script>alert(\"" .$filename . "\");</script>");
	
//session_cache_limiter('private_no_expire');
//session_cache_limiter('private');
//header('Pragma: private');
//header('Cache-control: private, must-revalidate');
//exit("<script>alert(\"" .$filename . "\");</script>");
header('Cache-Control: public');
header('Pragma: public');
	
	//header("Accept-Ranges: bytes");
	//header("Connection: Keep-Alive");
	header("Content-Length: ".filesize($path));
	header('Content-Type: application/force-download');
	//header('Content-Disposition: attachment; filename="'.urlencode($filename).'"');
	header('Content-Disposition: attachment; filename="'.$filename.'"');
	//header('Content-Disposition: attachment; filename='.'hbaabaoge'.'');
	readfile($path);
exit;
	//header('Content-Type: application/octet-stream');
	//header('Content-Disposition: inline; ');
//header("Content-Transfer-Encoding: binary");
	//header("Date: ".date( 'D, d M Y H:i:s' ,filemtime($path)) . ' GMT');
	//header('Etag: "'.md5_file($path).'"');
	//header( 'Expires: '.date( 'D, d M Y H:i:s' ,time()+10).' GMT');
	//header('Keep-Alive: timeout=1,max=99');
	//header( 'Last-Modified: Thu, 13 Dec 2007 11:21:21 GMT');
	//header('Cache-Control: max-age=1;');
	//header('Content-type: ');
	//header('Content-type: application/force-download');

//session_cache_limiter('private_no_expire');
////session_cache_limiter('private');
////header("Cache-Control: public"); 
//header('Pragma: private');
//header('Cache-control: private, must-revalidate');
//header('Cache-control: private, must-revalidate');
//header("Content-Description: File Transfer"); 
////header('Content-disposition: inline; filename="hoge.txt"'); 
//header('Content-disposition: attachment;'); 
//header("Content-Type: application/force-download"); 
//header("Content-Transfer-Encoding: binary"); 
//header('Content-Length: '. filesize($path)); 

	readfile($path);
	die;
}
else if (is_dir($path))
{
	$handle = opendir(LZ_BASEPATH.'cache/zip/');
	while( ($val = readdir($handle) ) !== false)
	{
		$_f = LZ_BASEPATH.'cache/zip/'.$val;
		if ($val == '.svn' || $val == '.' || $val == '..' || !is_file($_f)) continue;
		if (time() - filemtime($_f) > 600)
		{
			@unlink($_f);
		}
	}
	
	
	$fname = LZ_BASEPATH.'cache/_temp'.rand(1,9999).'.zip';
	$filename = $path;
	if (substr($filename,-1) == '/') $filename = substr($filename,0,-1);
	$filename = name_decode(basename($filename)).'.zip';
	$rnd = 'zip'.rand(1,999999);
//$_SESSION['hoge'] = '';
	folder_copy($path,$rnd);
//file_put_contents('/tmp/phptest.log', $_SESSION['hoge']);
//exit;
	
	$zip_file = LZ_BASEPATH."/cache/zip/{$rnd}.zip";
	$folder = LZ_BASEPATH."/cache/zip/$rnd/";
	
	$cmd = "cd ".escapeshellarg($folder).";zip -r ".escapeshellarg($zip_file)." . 2>&1";

	exec($cmd,$re,$st);
	if (file_exists($zip_file))
	{
		@exec("rm -r -f ".escapeshellarg($folder),$re);
session_cache_limiter('private_no_expire');
//session_cache_limiter('private');
header('Pragma: private');
header('Cache-control: private, must-revalidate');
		header('Content-type: application/x-octet-stream');
		header("Content-length: ".filesize($zip_file));
		header('Content-Disposition: attachment');
		//header('Content-Disposition: inline; ');
		
		readfile($zip_file);
		@unlink($zip_file);
		die;
	}
	else
	{
		$err = join('',$re);
		$err = addslashes($err);
		if (strpos($err,'Nothing') !== false)
		{
			exit("<script>alert('This is an empty folder!');</script>");
		}
		else
		{
			exit("<script>alert('Download Error:$err');</script>");
		}
	}
}

function folder_copy($path,$rnd,$rpath = '')
{
	global $config;
	if (substr($path,-1) != '/') $path.='/';
	if (!is_dir(LZ_BASEPATH."cache/zip/")) mkdir(LZ_BASEPATH."cache/zip/");
	if ($rpath && substr($rpath,-1) != '/') $rpath.='/';
	if (!is_dir(LZ_BASEPATH."cache/zip/$rnd/".$rpath)) mkdir(LZ_BASEPATH."cache/zip/$rnd/".$rpath);
	$handle = opendir($path);
	if (!$handle) exit('<script>alert("open dir error")</script>');
	while( ($val = readdir($handle) ) !== false)
	{
		//if (!preg_match('/^[a-zA-Z0-9,_=]{1,}$/',$val)) continue;
		if ($val == "." || $val == ".." || substr($val, 0, 1) == '.') {
			continue;
		}
		$rval = name_decode($val);
		if (strpos($_SERVER['HTTP_USER_AGENT'],'Mac') == false)
		{
//NT 5.0  ---> Windows 2000
//NT 5.1  ---> Windows XP
if (preg_match("/NT 5\.0/",$_SERVER['HTTP_USER_AGENT'])||preg_match("/NT 5\.1/",$_SERVER['HTTP_USER_AGENT'])){
$config['client_charset'] = 'cp932';
}
//$_SESSION['hoge'] .= 'RVAL:'.$rval . ':::' . 'ICONV:'.iconv('UTF-8',$config['client_charset'],$rval);
			$rval = iconv('UTF-8',$config['client_charset'],$rval);
		}
		if (is_dir($path.$val))
		{
			folder_copy($path.$val,$rnd,$rpath.$rval);
		}
		else if (is_file($path.$val))
		{
			cmd_cp($path.$val, LZ_BASEPATH."cache/zip/$rnd/".$rpath.$rval);
		}
	}
	closedir($handle);
}

function cmd_cp($file1,$file2)
{
	//$file1 = escapeshellarg($file1);
	//$file2 = escapeshellarg($file2);
	//exec("cp -L $file1 $file2",$re);
	//exec("cp \"$file1\" \"$file2\"",$re);
	copy($file1, $file2);
}

function cmd_rm($path)
{
	$path = escapeshellarg($path);
	exec('rm -r -f $path',$re);
}
?>
